<template>
  <Header />
  <div class="article-container">
    <!-- 文章信息和评论列表 -->
    <div class="info-and-comments">
      <el-card class="article-info">
        <div class="info-item">
          <el-icon><User /></el-icon>
          <span>作者：{{ article.username }}</span>
        </div>
        <div class="info-item">
          <el-icon><AlarmClock /></el-icon>
          <span>发布时间：{{ formatDate(article.createTime) }}</span>
        </div>
        <div class="info-item">
          <el-icon><Location /></el-icon>
          <span>最近更新：{{ formatDate(article.updateTime) }}</span>
        </div>
        <!-- 使用点赞组件，likeType 0 表示文章 -->
        <div class="info-item">
          <LikeButton :show-button="true" :targetId="articleId" :likeType="1" />
        </div>
      </el-card>

      <!-- 评论列表 -->
      <el-card class="comments-list">
        <div class="comments-title">评论</div>

        <!-- 主评论表单 -->
        <div class="comment-form">
          <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
          />
          <div class="form-actions">
            <el-button type="primary" @click="submitComment">发表评论</el-button>
          </div>
        </div>

        <CommentItem
            v-for="comment in comments"
            :key="comment.commentId"
            :comment="comment"
            :formatDate="formatDate"
            @reply-submitted="fetchComments"
        >
          <!-- 在 CommentItem 组件内添加点赞组件，likeType 2 表示评论 -->
          <template #like>
            <LikeButton :show-button="true" :targetId="comment.commentId" :likeType="2" />
          </template>
        </CommentItem>
      </el-card>
    </div>
    <!-- 文章内容 -->
    <el-card class="article-content">
      <div class="article-title">{{ article.title }}</div>
      <el-divider class="divider"/>
      <v-md-preview-html
          :html="html"
          preview-class="vuepress-markdown-body"
          @copy-code-success="handleCopyCodeSuccess"
      ></v-md-preview-html>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import Header from "@/components/Header.vue";
import { ElMessage } from "element-plus";
import VueMarkdownEditor, { xss } from '@kangc/v-md-editor';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
// 复制功能
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import request from "@/api/request";
import CommentItem from "@/components/CommentItem.vue";
import { getToken, parseToken } from "@/api/tokenDecode";
// 引入点赞组件
import LikeButton from '@/components/LikeButton.vue';

const formatDate = (date: Date) => {
  return new Date(date).toLocaleString()
}

VueMarkdownEditor.use(createLineNumbertPlugin());
VueMarkdownEditor.use(createCopyCodePlugin());

const handleCopyCodeSuccess = (code: any) => {
  ElMessage.success('已成功复制到剪切板')
  console.log(code);
}

interface Article {
  title: string;
  content: string;
  username: string;
  createTime: Date;
  updateTime: Date;
}

interface Comment {
  commentId: number;
  articleId: number;
  userId: number;
  parentCommentId: number | null;
  content: string;
  createTime: Date;
  nickname: string;
  userPic: string;
  children?: Comment[];
}

// 获取路由实例
const route = useRoute();
const html = ref(''); // 将 html 定义为响应式变量
// 用于存储当前文章
const article = ref({} as Article);
// 用于存储评论列表
const comments = ref([] as Comment[]);
// 获取文章 ID
const articleId = Number(route.params.id); // 从路由参数中获取 ID
const newComment = ref('');
const token = getToken();
const userInfo =  parseToken(token)?.claims
const replyTo = ref<number | null>(null);

const submitComment = async () => {
  if (!newComment.value.trim()) return;

  try {
    await request.post('/comments/add', {
      articleId: articleId,
      content: newComment.value,
      parentCommentId: null // 设置为null表示是顶级评论
    });

    ElMessage.success('评论成功');
    newComment.value = '';
    fetchComments();
  } catch (error) {
    ElMessage.error('评论失败');
    console.error('评论失败:', error);
  }
};

const handleReply = (payload: { parentId: number; content: string }) => {
  replyTo.value = payload.parentId;
  newComment.value = `回复 ${payload.parentId}: ${payload.content}`;
  // 自动聚焦到评论框
  setTimeout(() => {
    document.querySelector('.comment-form textarea')?.focus();
  }, 0);
};

const fetchComments = async () => {
  try {
    const response = await request.get('/comments/list', {
      params: { articleId: articleId }
    });
    comments.value = response.data;
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 在组件挂载时请求文章内容和评论列表
onMounted(() => {
  request.get('/article/getarticle', {
    params: {
      articleId: articleId,
    },
  })
      .then((response: any) => {
        article.value = response.data; // 设置文章数据
        const markdownContent = response.data.content; // 获取 Markdown 内容
        const renderedHtml = VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(markdownContent); // 渲染 Markdown
        html.value = xss.process(renderedHtml); // 使用 xss 处理渲染后的 HTML
      })
      .catch((error: any) => {
        console.error('获取文章失败:', error);
      });

  // 请求评论列表
  request.get('/comments/list', {
    params: {
      articleId: articleId,
    },
  })
      .then((response: any) => {
        comments.value = response.data; // 设置评论数据
      })
      .catch((error: any) => {
        console.error('获取评论失败:', error);
      });
  fetchComments();
});
</script>


<style scoped>

.comment-form {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.comment-form:hover {
  transform: translateY(-2px);
}

.form-actions {
  margin-top: 10px;
  text-align: right;
}

.form-actions .el-button {
  background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.form-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}

.article-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 20px;
  padding: 20px;
  max-width: 1400px;
  margin: 30px auto;
  background: linear-gradient(145deg, #f6f8fa 0%, #ffffff 100%);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.article-container:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}


.info-and-comments {
  display: flex;
  flex-direction: column;
}

.article-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 380px;
  height: fit-content;
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.comments-list {
  background: linear-gradient(145deg, #ffffff 0%, #f9fafb 100%);
  border-radius: 12px;
  margin-top: 30px;
  padding: 25px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
}

.comments-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 25px;
  color: #2d3748;
  position: relative;
  padding-bottom: 10px;
}

.comments-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50px;
  height: 3px;
  background: linear-gradient(to right, #409EFF, #67C23A);
  border-radius: 3px;
}

.comment-form {
  margin-bottom: 30px;
  background: rgba(248, 250, 252, 0.8);
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.comment-form:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
}




.article-content {
  background-color: #fff;
  border-radius: 8px;
  margin-top: 20px;
  padding: 30px;
  flex: 1;
  max-width: 900px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.article-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

.divider {
  margin: 0 0 25px 0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .article-container {
    flex-direction: column;
    align-items: center;
  }

  .article-info, .comments-list {
    width: 100%;
    max-width: 600px;
  }
}
</style>
